package com.cqhz.quwan.ui.login

import android.content.Intent
import android.text.Html
import com.cqhz.quwan.ActivityInject
import com.cqhz.quwan.R
import com.cqhz.quwan.common.KeyContract
import com.cqhz.quwan.model.AlipayAuthData
import com.cqhz.quwan.model.LoginBean
import com.cqhz.quwan.mvp.login.LoginContract
import com.cqhz.quwan.mvp.login.LoginPresenter
import com.cqhz.quwan.mvp.mine.AlipayContract
import com.cqhz.quwan.mvp.mine.AlipayPresenter
import com.cqhz.quwan.service.API
import com.cqhz.quwan.ui.base.GoBackActivity
import com.cqhz.quwan.ui.base.WebViewActivity
import com.cqhz.quwan.util.AuthResult
import com.cqhz.quwan.util.LoginObserver
import com.cqhz.quwan.util.LoginSubscribe
import io.reactivex.Flowable
import io.reactivex.android.schedulers.AndroidSchedulers
import kotlinx.android.synthetic.main.activity_login.*
import me.militch.quickcore.core.HasDaggerInject
import me.militch.quickcore.util.ApiException
import org.reactivestreams.Subscriber
import org.reactivestreams.Subscription
import java.util.concurrent.TimeUnit
import javax.inject.Inject


class LoginActivity : GoBackActivity(), LoginContract.BasicView, AlipayContract.View, HasDaggerInject<ActivityInject>, LoginSubscribe {

    @Inject
    lateinit var loginPresenter: LoginPresenter
    @Inject
    lateinit var alipayPresenter: AlipayPresenter
    var mSubscription: Subscription? = null
    private val oldTimes = 0

    override fun authLoginOk(loginBean: LoginBean) {

    }

    override fun login(loginBean: LoginBean?) {
        closePage()
    }

    override fun inject(t: ActivityInject?) {
        t?.inject(this)
    }

    override fun lockInputVerCode() {
        timer()
    }

    override fun showRequestError(e: ApiException) {
        super.showRequestError(e)
        action_get_code.isEnabled = true
    }

    private fun timer() {
        val count = 59L
        Flowable.interval(0, 1, TimeUnit.SECONDS)//设置0延迟，每隔一秒发送一条数据
                .onBackpressureBuffer()//加上背压策略
                .take(count) //设置循环次数
                .map { aLong ->
                    count - aLong //
                }
                .observeOn(AndroidSchedulers.mainThread())//操作UI主要在UI线程
                .subscribe(object : Subscriber<Long> {
                    override fun onSubscribe(s: Subscription?) {
                        action_get_code.isEnabled = false
                        action_get_code.setBackgroundResource(R.drawable.sp_gray_x15)
                        mSubscription = s
                        s?.request(Long.MAX_VALUE)//设置请求事件的数量，重要，必须调用
                    }

                    override fun onNext(aLong: Long?) {
                        action_get_code.text = "${aLong}s后重发" //接受到一条就是会操作一次UI
                    }

                    override fun onComplete() {
                        action_get_code.text = "点击重发"
                        action_get_code.isEnabled = true
                        action_get_code.setBackgroundResource(R.drawable.sp_red_x15)
                        mSubscription?.cancel()//取消订阅，防止内存泄漏
                    }

                    override fun onError(t: Throwable?) {
                        t?.printStackTrace()
                    }
                })
    }

    override fun layout(): Int {
        return R.layout.activity_login
    }

    override fun titleBarText(): String? {
        return "登录"
    }

    override fun initView() {
        alipayPresenter.attachView(this)
        loginPresenter.attachView(this)
        action_get_code.setOnClickListener {
            val tLength = et_phone.text?.length ?: -1
            if (tLength == 11) {
                loginPresenter.getVerCode(et_phone.text.toString())
                action_get_code.isEnabled = false
            } else {
                showToast("请输入正确的手机号码")
            }
        }
        action_login.setOnClickListener {

            val nLength = et_phone.text?.length ?: -1
            val cLength = et_code.text?.length ?: -1
            if (nLength == 11 && cLength == 6) {
                showLoading("正在登录中")
                loginPresenter.doLogin(et_phone.text.toString(), et_code.text.toString())
            } else {
                showToast("请输入正确的手机号码与验证码")
            }
        }
        tv_agreement.text = Html.fromHtml("注册代表您同意<font color='#1c7ee3'>《用户注册服务协议》</font>")

        tv_agreement.setOnClickListener {
            val intent = Intent(this, WebViewActivity::class.java)
            intent.putExtra(KeyContract.Title, "用户注册服务协议")
            val url = API.RegisterAgreement
            intent.putExtra(KeyContract.Url, url)
            startActivity(intent)
        }
        action_alipay_auth.setOnClickListener {
            alipayPresenter.auth4alipay()
        }
    }

    override fun onDestroy() {
        loginPresenter.detachView()
        alipayPresenter.detachView()
        LoginObserver.unregister(this)
        super.onDestroy()
    }

    override fun alipayAuthCallBack(authData: AlipayAuthData) {
        LoginObserver.register(this)
//        val intent = Intent(this,BindMobilePhoneActivity::class.java)
//        intent.putExtra(KeyContract.AlipayAuthData,authData)
//        startActivity(intent)
        loginPresenter.login4alipay(authData)
    }

    override fun alipayAuthFail(authResult: AuthResult) {
        super.alipayAuthFail(authResult)
        showToast(authResult.memo)
    }
}